﻿using System;

namespace Genko.Model
{
	public class Scheme : Member
	{
		public event ValidationEventHandler Validation;

		private SchemaSet schemas = null;
		private string name = null;
	
		public Scheme() : this("Scheme")
		{

		}
		
		public Scheme(string name)
		{
			this.name = name;
			this.schemas = new SchemaSet(this);
			this.Attach(this.schemas);
		}

		public virtual Member this[Guid guid]
		{
			get {
				return null;
			}
		}

		public virtual string Name
		{
			get { return this.name; }
		}

		public virtual SchemaSet Schemas
		{
			get { return this.schemas; }
		}

		public override bool CanBeAttached(Member member)
		{
			if (member is Model) {
				return true;
			}
			return (member is SchemaSet && !this.HasMembers);
		}

		public override Member CreateMember(string memberName)
		{
			return CreateModel(memberName);
		}

		public virtual Member CreateMember(Type memberType)
		{
			Member member = (Member)Activator.CreateInstance(memberType);
			member.owner = this;
			return member;
		}

		public virtual MetaModel CreateMetaModel(string metaModelName)
		{
			return Schemas.CreateMetaModel(metaModelName);
		}

		public virtual Model CreateModel(string metaModelName)
		{
			return Schemas.CreateModel(metaModelName);
		}

		public virtual IValidationNotifier CreateValidationNotifier()
		{
			return new SchemeValidationNotifier(this);
		}

		protected virtual void OnValidationNotifier(ValidationEventArgs args)
		{
			if (args.MessageType == ValidationMessageType.Error) {
				args.SourceMember.ValidationState = ValidationState.Invalid;
			}
			Validation(this, args);
		}

		internal class SchemeValidationNotifier : IValidationNotifier
		{
			private Scheme scheme = null;

			internal SchemeValidationNotifier(Scheme scheme)
			{
				this.scheme = scheme;
			}

			public void Notify(ValidationEventArgs args)
			{
				scheme.OnValidationNotifier(args);
			}
		}
	}
}
